<template>
	<view class="promotion-container">
		<!-- 推广统计卡片 -->
		<view class="stats-card">
			<view class="stats-header">
				<text class="stats-title">推广统计</text>
				<text class="stats-period">本月数据</text>
			</view>
			<view class="stats-grid">
				<view class="stat-item">
					<text class="stat-number">{{ promotionStats.clickCount }}</text>
					<text class="stat-label">访问量</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">{{ promotionStats.direct_addnum }}</text>
					<text class="stat-label">注册数</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">{{ promotionStats.direct_salenum }}</text>
					<text class="stat-label">下单数</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">{{ promotionStats.conversion }}</text>
					<text class="stat-label">转化率</text>
				</view>
			</view>
		</view>

		<!-- 推广链接卡片 -->
		<view class="link-card">
			<view class="card-header">
				<text class="card-title">我的推广链接</text>
				<!-- <button class="refresh-btn" @click="refreshLink">
					<text class="refresh-icon">🔄</text>
				</button> -->
			</view>

			<view class="link-section">
				<text class="link-label">推广链接：</text>
				<view class="link-container">
					<text class="link-text">{{ promotionLink }}</text>
					<button class="copy-btn" @click="copyLink">复制</button>
				</view>
			</view>

			<view class="link-section">
				<text class="link-label">邀请码：</text>
				<view class="code-container">
					<text class="code-text">{{ inviteCode }}</text>
					<button class="copy-btn" @click="copyCode">复制</button>
				</view>
			</view>
		</view>

		<!-- 二维码卡片 -->
		<view class="qrcode-card">
			<view class="card-header">
				<text class="card-title">推广二维码</text>
				<view class="qrcode-actions">
					<button class="action-btn" @click="downloadQRCode">下载</button>
					<button open-type="share" class="action-btn">分享</button>
				</view>
			</view>

			<view class="qrcode-container">
				<view class="qrcode-wrapper">
					<!-- 这里应该是真实的二维码组件 -->
					<view class="qrcode-placeholder">
						<canvas canvas-id="qrcode" :style="{ width: (size+40) + 'rpx', height: (size+40) + 'rpx' }"
							class="qr-canvas" />
					</view>
				</view>
				<view class="qrcode-info">
					<text class="qrcode-desc">扫码注册成为我的下级分销员</text>
					<text class="qrcode-tip">长按保存图片分享给好友</text>
				</view>
			</view>
		</view>

		<!-- 推广素材 -->
		<view class="material-card">
			<view class="card-header">
				<text class="card-title">推广素材</text>
				<text class="more-link" @click="toMaterialList">查看更多</text>
			</view>

			<view class="material-grid">
				<view class="material-item" v-for="(material, index) in materials" :key="index"
					@click="previewMaterial(material)">
					<image :src="$tools.buildUrl(material.white_back_ground_pic_url)" class="material-image"
						mode="aspectFill" />
					<view class="material-info">
						<text class="material-title">{{ material.spu_name }}</text>
						<text class="material-type">{{ material.group_name }}</text>
					</view>
					<view class="material-actions">
						<button class="material-btn" @click.stop="downloadMaterial(material)">
							下载
						</button>
						<button open-type="share" class="material-btn" :data-material="material">
							分享
						</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 推广记录 -->
		<!-- <view class="record-card">
			<view class="card-header">
				<text class="card-title">推广记录</text>
				<text class="more-link" @click="toRecordList">查看全部</text>
			</view>

			<view class="record-list">
				<view class="record-item" v-for="(record, index) in promotionRecords" :key="index">
					<view class="record-avatar">
						<image v-if="record.avatar" :src="record.avatar" class="avatar-image" mode="aspectFill" />
						<view v-else class="avatar-placeholder">
							<text class="avatar-text">{{ record.name.charAt(0) }}</text>
						</view>
					</view>
					<view class="record-info">
						<text class="record-name">{{ record.name }}</text>
						<text class="record-action">{{ record.action }}</text>
						<text class="record-time">{{ record.time }}</text>
					</view>
					<view class="record-reward" v-if="record.reward">
						<text class="reward-text">+{{ record.reward }}</text>
					</view>
				</view>
			</view>
		</view> -->
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import UQRCode from 'uqrcodejs';

	export default {
		data() {
			return {
				size: 200, // 二维码大小
				// 推广统计
				promotionStats: {
					clickCount: '0',
					direct_addnum: '0',
					direct_salenum: '0',
					conversion: '0.0%'
				},
				// 推广链接
				promotionLink: '',
				// 邀请码
				inviteCode: '',
				// 推广素材
				materials: [],
				// 分享产品信息
				shareInfo: {},
				tempFilePath: '',
				// 推广记录
				// promotionRecords: [{
				// 		id: 1,
				// 		name: '张小明',
				// 		avatar: '',
				// 		action: '通过您的链接注册',
				// 		time: '2024-03-15 14:30',
				// 		reward: '10积分'
				// 	},
				// 	{
				// 		id: 2,
				// 		name: '李小红',
				// 		avatar: '',
				// 		action: '首次下单',
				// 		time: '2024-03-14 16:20',
				// 		reward: '50积分'
				// 	},
				// 	{
				// 		id: 3,
				// 		name: '王小华',
				// 		avatar: '',
				// 		action: '通过您的链接访问',
				// 		time: '2024-03-14 10:15',
				// 		reward: ''
				// 	}
				// ]
			}
		},

		computed: {
			...mapGetters(['isLogin', 'userInfo', 'dealerInfo'])
		},

		mounted() {
			this.generateQRCode();
		},

		onLoad() {
			this.inviteCode = this.$secret.encryptAES(this.userInfo.id);
			this.promotionLink = 'http://www.gxwzlbc.com/invite?inviteCode=' + this.inviteCode;
			this.loadUserPromotion();
			this.loadProductLunBo();
		},

		// 微信小程序分享配置
		onShareAppMessage(event) {
			// 分销员审核状态：-1待审核 0未审核 1审核中 2审核通过 2驳回
			if (!this.userInfo.check_status || this.userInfo.check_status !== 2) {
				return
			}
			// 获取页面栈实例数组
			const pages = getCurrentPages();
			// 获取当前页面实例（最后一个元素）
			const currentPage = pages[pages.length - 1];
			// 获取页面路径
			let pagePath = '/pages/index/index';
			// 分享人信息（邀请码：inviteCode）
			let inviteCode = ''
			if (this.userInfo && Number(this.userInfo.id) > 0) {
				inviteCode = this.$secret.encryptAES(this.userInfo.id)
			}
			// 分享的页面路径
			let sharePath = `${pagePath}?inviteCode=${inviteCode}`
			// 当前分享的内容
			this.shareInfo = event.target.dataset.material;
			// 显示图片优先级: 商品 -- 店铺  -- 默认
			let imageUrl = '';
			if (this.shareInfo && this.shareInfo.white_back_ground_pic_url != '') {
				pagePath = '/pages/product/detail'
				sharePath = `${pagePath}?id=${this.shareInfo.id}&inviteCode=${inviteCode}`
				imageUrl = this.$tools.buildUrl(this.shareInfo.white_back_ground_pic_url)
			} else if (this.tempFilePath && this.tempFilePath != '') {
				imageUrl = this.tempFilePath
			} else if (this.dealerInfo && this.dealerInfo.shop_logo != '') {
				const dealerCode = this.$secret.encryptAES(this.dealerInfo.company_id)
				sharePath = `${pagePath}?dealerCode=${dealerCode}&inviteCode=${inviteCode}`
				imageUrl = this.$tools.buildUrl(this.dealerInfo.shop_logo)
			} else {
				imageUrl = this.$tools.buildUrl('/static/images/product.png')
			}

			return {
				title: `${this.dealerInfo.shop_name} - 优质六堡茶专营`,
				path: sharePath,
				imageUrl: imageUrl,
				miniprogramType: 1,
				success: res => {
					// 用户点击了“发送”按钮（分享成功）
					// console.log('分享成功', res);
					// 任务类型：1 - 注册积分 2 - 推荐积分 3 - 分享积分 4 - 消费积分 5 - 签到积分
					this.$api.point.CompletePointsTask({
						task_type: 3,
						task_desc: `分享了${this.dealerInfo.shop_name} - ${this.shareInfo.spu_name}`
					}).then(res => {
						uni.showToast({
							title: res.msg,
							icon: 'success'
						})
					})
				},
				fail: err => {
					// 用户取消分享或发送失败
					// console.log('分享失败', err);
				}
			};
		},

		// 分享到朋友圈配置
		onShareTimeline(event) {
			// 分销员审核状态：-1待审核 0未审核 1审核中 2审核通过 2驳回
			if (!this.userInfo.check_status || this.userInfo.check_status !== 2) {
				return
			}
			// 分享人信息（邀请码：inviteCode）
			let inviteCode = ''
			if (this.userInfo && Number(this.userInfo.id) > 0) {
				inviteCode = this.$secret.encryptAES(this.userInfo.id)
			}
			// 分享参数
			let shareQuery = `inviteCode=${inviteCode}`
			// 当前分享的内容
			this.shareInfo = event.target.dataset.material;
			// 显示图片优先级: 商品 -- 店铺  -- 默认
			let imageUrl = ''
			if (this.shareInfo && this.shareInfo.white_back_ground_pic_url != '') {
				shareQuery = `id=${this.shareInfo.id}&inviteCode=${inviteCode}`
				imageUrl = this.$tools.buildUrl(this.shareInfo.white_back_ground_pic_url)
			} else if (this.tempFilePath && this.tempFilePath != '') {
				imageUrl = this.tempFilePath
			} else if (this.dealerInfo && this.dealerInfo.shop_logo != '') {
				const dealerCode = this.$secret.encryptAES(this.dealerInfo.company_id)
				shareQuery = `dealerCode=${dealerCode}&inviteCode=${inviteCode}`
				imageUrl = this.$tools.buildUrl(this.dealerInfo.shop_logo)
			} else {
				imageUrl = this.$tools.buildUrl('/static/images/product.png')
			}

			return {
				title: `${this.dealerInfo.shop_name} - 优质六堡茶专营`,
				query: shareQuery,
				imageUrl: imageUrl,
				success: res => {
					// 用户点击了“发送”按钮（分享成功）					
					// console.log('分享成功', res);
					// 任务类型：1 - 注册积分 2 - 推荐积分 3 - 分享积分 4 - 消费积分 5 - 签到积分
					this.$api.point.CompletePointsTask({
						task_type: 3,
						task_desc: `分享了${this.dealerInfo.shop_name} - ${this.shareInfo.spu_name}`
					}).then(res => {
						uni.showToast({
							title: res.msg,
							icon: 'success'
						})
					})
				},
				fail: err => {
					// 用户取消分享或发送失败
					// console.log('分享失败', err);
				}
			};
		},

		methods: {
			// 获取用户推广统计
			loadUserPromotion() {
				this.$api.fenxiao.GetUserPromotion().then(res => {
					if (res.data && res.data.id > 0) {
						this.promotionStats = res.data
					} else if (res.data && res.data.clickCount) {
						this.promotionStats.clickCount = res.data.clickCount
					}
					if (this.promotionStats.clickCount > 0) {
						this.promotionStats.conversion = (parseInt(this.promotionStats.direct_salenum) / parseInt(
							this.promotionStats.clickCount) * 100).toFixed(1) + '%'
					} else {
						this.promotionStats.conversion = '0.0%'
					}
				})
			},
			// 获取推广素材（首页轮播产品）
			loadProductLunBo() {
				this.$api.good.GetProductLunBo().then(res => {
					this.materials = res.data
				})
			},
			// 刷新推广链接
			refreshLink() {
				uni.showLoading({
					title: '刷新中...'
				})

				this.inviteCode = this.$secret.encryptAES(this.userInfo.id);
				this.promotionLink = 'http://www.gxwzlbc.com/invite?inviteCode=' + this.inviteCode;
				this.generateQRCode();

				uni.hideLoading();
				uni.showToast({
					title: '链接已刷新',
					icon: 'success'
				})
			},

			// 复制推广链接
			copyLink() {
				uni.setClipboardData({
					data: this.promotionLink,
					success: () => {
						uni.showToast({
							title: '链接已复制',
							icon: 'success'
						})
					}
				})
			},

			// 复制邀请码
			copyCode() {
				uni.setClipboardData({
					data: this.inviteCode,
					success: () => {
						uni.showToast({
							title: '邀请码已复制',
							icon: 'success'
						})
					}
				})
			},

			generateQRCode() {
				const qr = new UQRCode();
				qr.data = this.promotionLink; // 二维码内容
				qr.size = 130; // 尺寸需与 canvas 一致
				qr.margin = 5;
				qr.foregroundColor = '#000000';
				qr.backgroundColor = '#FFFFFF';

				// 添加logo
				// 最佳实践：
				// 1. 尺寸：80×80像素
				// 2. 格式：PNG（带透明背景）
				// 3. 颜色：单色或简单双色
				const logoUrl = this.$tools.buildUrl(this.userInfo.avatar_url)
				if (logoUrl && logoUrl != '') {
					qr.logo = logoUrl;
					qr.logoScale = 0.2; // logo占二维码比例										
				}

				qr.make(); // 生成二维码
				const ctx = uni.createCanvasContext('qrcode', this); // 组件需传 this
				qr.canvasContext = ctx;
				qr.drawCanvas();
			},

			downloadQRCode() {
				// 将Canvas转换为临时图片
				uni.canvasToTempFilePath({
					canvasId: 'qrcode',
					success: (res) => {
						this.tempFilePath = res.tempFilePath;
						uni.getSetting({
							success: (res2) => {
								if (!res2.authSetting['scope.writePhotosAlbum']) {
									// 申请权限
									uni.authorize({
										scope: 'scope.writePhotosAlbum',
										success: () => {
											this.saveImage(this.tempFilePath)
										}
									});
								} else {
									// 保存到相册
									this.saveImage(this.tempFilePath);
								};
							}
						});
					},
					fail: (err) => {
						console.error('转换失败:', err);
						uni.showToast({
							title: '生成图片失败',
							icon: 'none'
						});
					}
				}, this);
			},

			// 预览推广素材
			previewMaterial(material) {
				const url = this.$tools.buildUrl(material.white_back_ground_pic_url)
				uni.previewImage({
					urls: [url],
					current: url
				})
			},

			// 下载推广素材
			downloadMaterial(material) {
				const url = this.$tools.buildUrl(material.white_back_ground_pic_url)
				uni.getSetting({
					success: (res) => {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							// 申请权限
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success: () => {
									this.saveImage(url)
								}
							});
						} else {
							// 保存到相册
							this.saveImage(url);
						};
					}
				});
			},

			// 保存到相册
			saveImage(url) {
				uni.saveImageToPhotosAlbum({
					filePath: url,
					success: () => {
						uni.showToast({
							title: '保存成功'
						})
					},
					fail: () => {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						})
					}
				});
			},

			// 分享推广素材
			shareMaterial(material) {
				this.shareInfo = material
			},

			// 跳转到素材列表
			toMaterialList() {
				uni.switchTab({
					url: '/pages/category/category'
				})
			},

			// 跳转到推广记录
			toRecordList() {
				uni.navigateTo({
					url: '/fenxiao-package/distribution/promotion-record'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.promotion-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		padding: 20rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}

	/* 统计卡片 */
	.stats-card {
		background-color: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.stats-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.stats-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.stats-period {
		font-size: 24rpx;
		color: #999;
	}

	.stats-grid {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 20rpx;
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.stat-number {
		font-size: 32rpx;
		font-weight: bold;
		color: #52a58a;
		margin-bottom: 8rpx;
	}

	.stat-label {
		font-size: 24rpx;
		color: #666;
	}

	/* 通用卡片样式 */
	.link-card,
	.qrcode-card,
	.material-card,
	.record-card {
		background-color: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.card-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.refresh-btn {
		background: none;
		border: none;
		padding: 0;
		font-size: 24rpx;
	}

	.refresh-icon {
		font-size: 24rpx;
	}

	.more-link {
		font-size: 24rpx;
		color: #52a58a;
	}

	/* 链接区域 */
	.link-section {
		margin-bottom: 30rpx;
	}

	.link-section:last-child {
		margin-bottom: 0;
	}

	.link-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		display: block;
	}

	.link-container,
	.code-container {
		display: flex;
		align-items: center;
		background-color: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx;
	}

	.link-text,
	.code-text {
		flex: 1;
		font-size: 26rpx;
		color: #666;
		word-break: break-all;
	}

	.copy-btn {
		background-color: #52a58a;
		color: white;
		border: none;
		border-radius: 8rpx;
		padding: 12rpx 24rpx;
		font-size: 24rpx;
		margin-left: 20rpx;
	}

	/* 二维码区域 */
	.qrcode-actions {
		display: flex;
		gap: 16rpx;
	}

	.action-btn {
		background-color: #52a58a;
		color: white;
		border: none;
		border-radius: 8rpx;
		padding: 12rpx 24rpx;
		font-size: 24rpx;
	}

	.qrcode-container {
		display: flex;
		align-items: center;
	}

	.qrcode-wrapper {
		width: 260rpx;
		height: 260rpx;
		margin-right: 30rpx;
		text-align: center;
	}

	.qrcode-placeholder {
		width: 100%;
		height: 100%;
		background-color: #f8f9fa;
		border: 2rpx dashed #ddd;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.qrcode-text {
		font-size: 24rpx;
		color: #999;
	}

	.qrcode-info {
		flex: 1;
	}

	.qrcode-desc {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		display: block;
	}

	.qrcode-tip {
		font-size: 24rpx;
		color: #999;
	}

	.qr-canvas {
		/* 确保 Canvas 可见 */
		display: block;
		background: white;
	}

	/* 推广素材 */
	.material-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
	}

	.material-item {
		border: 1rpx solid #f0f0f0;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.material-image {
		width: 100%;
		height: 200rpx;
	}

	.material-info {
		padding: 20rpx;
	}

	.material-title {
		font-size: 26rpx;
		color: #333;
		margin-bottom: 8rpx;
		display: block;
	}

	.material-type {
		font-size: 22rpx;
		color: #999;
	}

	.material-actions {
		display: flex;
		padding: 0 20rpx 20rpx;
		gap: 16rpx;
	}

	.material-btn {
		flex: 1;
		background-color: #52a58a;
		color: white;
		border: none;
		border-radius: 8rpx;
		padding: 12rpx 0;
		font-size: 24rpx;
	}

	/* 推广记录 */
	.record-list {}

	.record-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.record-item:last-child {
		border-bottom: none;
	}

	.record-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		margin-right: 20rpx;
		overflow: hidden;
	}

	.avatar-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.avatar-placeholder {
		width: 100%;
		height: 100%;
		background-color: #52a58a;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.avatar-text {
		color: white;
		font-size: 24rpx;
		font-weight: bold;
	}

	.record-info {
		flex: 1;
	}

	.record-name {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 8rpx;
		display: block;
	}

	.record-action {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 4rpx;
		display: block;
	}

	.record-time {
		font-size: 22rpx;
		color: #999;
	}

	.record-reward {
		padding: 8rpx 16rpx;
		background-color: #fff5f0;
		border-radius: 12rpx;
	}

	.reward-text {
		font-size: 24rpx;
		color: #ff6b35;
		font-weight: bold;
	}
</style>